package com.atguigu.gmall.common.config.thread;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;


@Configuration
public class AppThreadPoolConfig {

    @Bean
    public ThreadPoolExecutor coreThreadPool(AppThreadPoolProperties properties) {
        /**
         * int corePoolSize,
         * int maximumPoolSize,
         * long keepAliveTime,
         * TimeUnit unit, //分钟
         * BlockingQueue<Runnable> workQueue,
         * ThreadFactory threadFactory,
         * RejectedExecutionHandler handler
         */
        return new ThreadPoolExecutor(properties.getCorePoolSize(),
                properties.getMaximumPoolSize(),
                properties.getKeepAliveTime(),
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(properties.getQueueSize()),
                new ThreadFactory() {
                    int i = 1;

                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = new Thread(r);
                        thread.setName("[service-item]core-thread-pool-" + i++);
                        return thread;
                    }
                }, new ThreadPoolExecutor.CallerRunsPolicy());
    }
}
